package service

import (
	"fmt"
	"io/ioutil"
	"log"
	"nacos-prometheus-discovery/httputil"
	"nacos-prometheus-discovery/model"
	"os"
	"sync"
)

func FetchPrometheusConfig(config model.Config) {
	nacosHost := config.NacosHost
	namespaceId := config.NamespaceId
	group := config.Group
	//cluster := config.Cluster
	tenant := config.NamespaceId

	configList := config.ConfigList
	var wg sync.WaitGroup
	wg.Add(len(configList))
	for _, item := range configList {
		targetFilePath := item.TargetFilePath
		dataId := item.DataId
		log.Printf("targetFilePath:%s,dataId:%s", targetFilePath, dataId)
		go createConfigFile(wg, nacosHost, tenant, namespaceId, dataId, group, targetFilePath)
	}
}

func createConfigFile(wg sync.WaitGroup, nacosHost string, tenant string, namespaceId string, dataId string, group string, targetFilePath string) {
	defer wg.Done()
	configString := GetConfig(nacosHost, tenant, namespaceId, dataId, group)
	log.Println("configString:", configString)

	wfErr := ioutil.WriteFile(targetFilePath, []byte(configString), os.ModePerm)
	if wfErr != nil {
		log.Println("generate target file failed", wfErr)
	}
}

func GetConfig(nacosHost, tenant, namespaceId, dataId, group string) string {
	configUrl := fmt.Sprintf("%s/v1/cs/configs?tenant=%s&namespaceId=%s&dataId=%s&group=%s", nacosHost, tenant, namespaceId, dataId, group)
	log.Println("=== configUrl:", configUrl)

	config, serr := httputil.Get(configUrl)
	if serr != nil {
		log.Println("get config failed", serr)
	}
	return config
}
